package com.sangeng.handler.exception;

import com.sangeng.domain.ResponseResult;
import com.sangeng.enums.AppHttpCodeEnum;
import com.sangeng.exception.SystemException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

//统一处理异常信息
/*
 * 请求先经过过滤器，springsecurity的认证授权异常处理器先捕获，等到请求被SpringMVC接管了，出现异常就会交给这个统一异常处理
 *
 * */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SystemException.class)//传入处理的对应异常的字节码对象
    public ResponseResult<String> systemExceptionHandler(SystemException e) {
        //打印异常信息
        log.error("出现了异常！ {}", e);
        //从异常对象中获取提示信息封装返回
        return ResponseResult.errorResult(e.getCode(), e.getMsg());
    }


    //处理system异常以外的其他异常
    @ExceptionHandler(Exception.class)
    public ResponseResult<String> exceptionHandler(Exception e) {
        //打印异常信息
        log.error("出现了异常！ {}", e);
        //从异常对象中获取提示信息封装返回
        return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(), e.getMessage());
              //  .substring(e.getMessage().lastIndexOf("["), e.getMessage().lastIndexOf("]")));
    }

    //处理validation异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<String> exceptionHandler(MethodArgumentNotValidException e) {
        //打印异常信息
        log.error("出现了异常！ {}", e);

        BindingResult br = e.getBindingResult();
        StringBuilder msgStr = new StringBuilder();
        List<FieldError> feList = br.getFieldErrors();
        for (FieldError fe : feList) {
            String message = fe.getDefaultMessage();
            String field = fe.getField();
            msgStr.append(field).append(message).append("; ");
        }
        //从异常对象中获取提示信息封装返回
        return ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(), msgStr.toString());
    }
}
